package com.woniuxy.ticketauth.controller;

import com.woniuxy.commnes.entity.ResponseResult;
import com.woniuxy.ticketauth.entity.Manager;
import com.woniuxy.ticketauth.entity.Perm;
import com.woniuxy.ticketauth.jwt.Audience;
import com.woniuxy.ticketauth.jwt.JwtUtil;
import com.woniuxy.ticketauth.service.PermService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author zx
 * @Date 2021-03-02 15:22:06
 * @Version 1.0
 */
//@CrossOrigin解决跨域问题
@CrossOrigin(exposedHeaders = "*")  //exposedHeaders = "Authorization"暴露Authorization响应头,应许前台获取
@RestController
@RequestMapping("manager")
public class ManagerController {

    @Resource
    private Audience audience;

    @Resource
    private PermService permService;

    //生成Jwt
    @PostMapping("login")
    public ResponseResult<Void> login(String account, String password, HttpServletResponse response) {
        UsernamePasswordToken token = new UsernamePasswordToken(account,password );

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            Map<String, String> map = new ConcurrentHashMap<>();
        }catch (UnknownAccountException e){
            return new ResponseResult<>(404,"账号不存在");
        }catch (IncorrectCredentialsException e){
            return new ResponseResult<>(504,"密码不正确");
        }
        Manager manager = (Manager)subject.getPrincipal();
//        int id = 1;
        //产生jwt
        String jwt = JwtUtil.createJWT(manager.getId(),account,audience);
        //添加响应头
        response.setHeader("Authorization",jwt);
        return ResponseResult.SUCCESS;
    }

    /**
     * 获取Token中的用户信息
     * @param jwt
     * @return
     */
    @PostMapping("addorder")
    public ResponseResult<Void> addOrder(@RequestHeader("jwt") String jwt){
        if (JwtUtil.parseJwt(jwt,audience.getBase64Secret())){
            int id =JwtUtil.getUserId(jwt,audience.getBase64Secret());
            String account =JwtUtil.getAccount(jwt,audience.getBase64Secret());
            return ResponseResult.SUCCESS;
        }
        return ResponseResult.ERR;
    }

    @PostMapping("findId")
    public ResponseResult<?> testFind(int id){

        return new ResponseResult<Perm>(200,"成功",permService.getById(id));
    }
}
